import { ApartmentOutlined } from '@ant-design/icons';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { i18n, nmAppErrorLog, setObject } from '@app-nextmesh/common/utils';
import { showLoading } from '@app-nextmesh/components';
import {
  FormField,
  FormNativeSelect,
} from '@app-nextmesh/components/Forms/components';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import { useTasksStore } from '@app-nextmesh/store/tasks';
import { ITask } from '@app-nextmesh/types';
import { Button, Modal } from 'antd';
import { useEffect, useState } from 'react';

interface IProps {
  count: number;
  onOk: (newData: ITask) => void;
  onClose: () => void;
}

export default function TaskAddDialog({ count, onOk, onClose }: IProps) {
  const [data, setData] = useState<any>({});
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { tasks, setTasks } = useTasksStore();
  const simulations = useProjectStore(
    (state) => state.projectInfo?.simulations,
  );

  useEffect(() => {
    const newData = { name: `${i18n.t('task')}${count + 1}` };
    setData(newData);

    showModal();
  }, [count]);
  const handleInputChange = (name: string, value: string) => {
    const newData = { ...data };
    setObject(newData, name, value);
    setData(newData);
  };
  const handleOk = async () => {
    const hide = showLoading();
    try {
      if (!data.name || !data.simuId) {
        MessageTip.error(i18n.t('pleaseSelectSimulation'));
        return;
      }
      const newTask = await documentV2.addTask(data);
      setIsModalOpen(false);
      // 最新的在最前面，插入数组头部
      tasks.unshift(newTask);
      setTasks([...tasks]);
      onOk(newTask);
    } catch (error) {
      nmAppErrorLog('TaskAddDialog', 'handleOk', error);
    } finally {
      hide();
    }
  };
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    // #464681
    setIsModalOpen(false);
    onClose();
  };
  const options =
    simulations?.map((s) => ({ label: s.name, value: s.uuid })) || [];
  return (
    <Modal
      title={
        <div>
          <ApartmentOutlined style={{ marginRight: 10, color: '#e0893d' }} />
          {i18n.t('createTask')}
        </div>
      }
      closable={false}
      open={isModalOpen}
      footer={[
        <Button
          key='back'
          onClick={handleCancel}
        >
          取消
        </Button>,
        <Button
          key='submit'
          type='primary'
          onClick={handleOk}
        >
          创建
        </Button>,
      ]}
    >
      <FormField label={i18n.t('selectSimulation')}>
        <FormNativeSelect
          value={data?.simuId}
          options={options}
          onChange={(value) => handleInputChange('simuId', value as string)}
        />
      </FormField>
    </Modal>
  );
}
